<?php
declare (strict_types=1);

namespace app\controller;

use app\BaseController;
use app\helpers\traits\ImageUpload;
use app\helpers\traits\SearchDataForModel;
use app\model\IssueCategory;
use app\model\IssueQuestion;
use app\model\IssueQuestionAnswer;
use app\model\QuestionInfo;
use app\model\Questionnaire;
use app\model\QuestionWrite;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Request;

class Question extends BaseController
{
    use SearchDataForModel, ImageUpload;

    /**
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 11:57
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 问卷列表
     */
    public function getQuestionList()
    {
        $limit = $this->request->param('limit', 10);
//        $map[] = array('status','=',1);
        $res = $this->search(new Questionnaire(), [], $limit, 'asc');
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 12:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存
     */
    public function saveQuestion()
    {

        $id = $this->request->param('id', 0);
        $data = $this->request->param();
        $data['create_id'] = $this->request->uid;
        if (intval($id) === 0) {
            Questionnaire::create($data);
        } else {
            $question = Questionnaire::find($id);
            $question->save($data);
        }
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 14:05
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除
     */
    public function QuestionDel($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            $data = Questionnaire::find($id);
            if (is_null($data)) {
                return $this->response(404, '此问卷不存在');
            }
            $data->delete();
        }
        return $this->response();
    }


    /**
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 17:40
     * @return \think\response\Json
     * 导入问卷
     */
    public function importExcel()
    {
        $questionnaire_id = $this->request->param('questionnaire_id');
        if (!$this->request->file('file')) {
            return $this->response(501, '请选择上传文件');
        }
        $file = $this->request->file('file');
        $result = $this->saveImportExcel($file, 'import_excel');
        $is_bool = Questionnaire::saveQuestionnaireArr($result, $questionnaire_id);
        if ($is_bool === true) {
            $questionnaire = Questionnaire::find($questionnaire_id);
            if (is_null($questionnaire)) {
                return $this->response(403, '导入问卷失败');
            }
            $questionnaire->save(['status' => Questionnaire::STATUS_ONE]); //更改状态
            return $this->response();
        } else {
            return $this->response(403, '导入问卷失败');
        }
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 18:36
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取问卷
     */
    public function getCheckQuestionInfo()
    {
        $id = $this->request->param('id', 0);
        $questionnaire = Questionnaire::find($id);
        if (is_null($questionnaire)) {
            return $this->response(403, '问卷获取失败');
        }
        $res = IssueCategory::with(['questions' => ['questionAnswers']])->where(['questionnaire_id' => $id])->select();
        foreach ($res as $key => $v) {
            foreach ($v['questions'] as $k1 => $v1) {
                $v1['issue_question_type_name'] = IssueQuestion::$issue_question_type_arr_string[$v1['issue_question_type']] ?? '暂未匹配';
                foreach ($v1['questionAnswers'] as $k2 => $v2) {
                    $v2['issue_answer_type_name'] = IssueQuestionAnswer::$issue_answer_type_arr_string[$v2['issue_answer_type']] ?? '暂未匹配';
                    $v2['is_write_name'] = IssueQuestionAnswer::$is_write_arr_string[$v2['is_write']] ?? '暂未匹配';
                }
            }
        }
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 19:34
     * @return \think\response\Json
     * 获取题目类型
     */
    public function getSelectTypeData()
    {
        $res = IssueQuestion::$issue_question_type_arr_string;
        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 19:46
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 改变题目类型
     */
    public function saveChangeType()
    {
        $data = $this->request->param();
        $res = IssueQuestion::find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '找不到该问题');
        }
        $res->save($data);
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 20:03
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 改变是否终止
     */
    public function changeAnswerType($id)
    {
        $data = IssueQuestionAnswer::find($id);

        if (is_null($data)) {
            return $this->response(403, '不存在');
        }
        $is_start = $data->issue_answer_type === 2 ? 1 : 2;
        $data->save(['issue_answer_type' => $is_start]);
        return $this->response();
    }

    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/8/16
     * @Time: 20:08
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 是否需要自定义填写
     */
    public function changeIsWrite($id)
    {
        $data = IssueQuestionAnswer::find($id);

        if (is_null($data)) {
            return $this->response(403, '不存在');
        }
        $is_start = $data->is_write === 0 ? 1 : 0;
        $data->save(['is_write' => $is_start]);
        return $this->response();
    }


    public function questionOneList()
    {
        $id = $this->request->param('id', 5);
        $questionnaire = Questionnaire::find($id);
        if (is_null($questionnaire)) {
            return $this->response(403, '不存在');
        }
        $new_arr = [];
        $res = IssueQuestion::with(['questionAnswers'])->where(['questionnaire_id' => $id])->select()->toArray();
        foreach ($res as $key => $v) {
            $new_arr[$key]['id'] = $v['id'];
            $new_arr[$key]['title'] = $v['issue_question_title'];
            $new_arr[$key]['type'] = $v['issue_question_type'];
            $optionList = [];
            foreach ($v['questionAnswers'] as $k1 => $v2) {
                $optionList[$k1]['id'] = $v2['id'];
                $optionList[$k1]['content'] = $v2['issue_answer_title'];
                $optionList[$k1]['issue_answer_type'] = $v2['issue_answer_type'];
                $optionList[$k1]['is_write'] = $v2['is_write'];
                $optionList[$k1]['jump_topic'] = $v2['jump_topic'];
            }
            $new_arr[$key]['optionList'] = $optionList;
            $new_arr[$key]['answer'] = '';
            $new_arr[$key]['userAnswer'] = '';
            $new_arr[$key]['userRea'] = ''; //选择其他的时候备注
            $new_arr[$key]['userFavor'] = false;
            $new_arr[$key]['explain'] = '';
        }
        return $this->response($new_arr);

    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/17
     * @Time: 16:21
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 获取答案的状态
     */
    public function getQuestionAnswer()
    {
        $id = $this->request->param();
        $res = IssueQuestionAnswer::find($id);
        if (is_null($res)) {
            return $this->response(403, '不存在');
        }

        return $this->response($res);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/18
     * @Time: 11:57
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 多选判断
     */
    public function getQuestionAnswerType()
    {
        $data = $this->request->param();
        $ids = rtrim($data['ids'], ',');
        $ids_arr = explode(',', $ids);
        $map[] = array('id', 'in', $ids_arr);
        $new_string = '';
        $res = IssueQuestionAnswer::field('id,issue_answer_title,is_write')->where($map)->select()->toArray();
        foreach ($res as $key => $v) {
            $new_string .= $v['is_write'] . ',';
        }
        $result = ['ids' => rtrim($new_string, ',')];

        return $this->response($result);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/8/17
     * @Time: 19:27
     * @return \think\response\Json
     * 保存回答的问题
     */
    public function saveQuestionInfoAndWrite()
    {
        $data = $this->request->param();
        $question_info_id = 0;
        if (isset($data['info'])) {
            $question_info_id = QuestionInfo::create($data['info'])->id;
        }
        if (isset($data['write'])) {
            foreach ($data['write'] as $key => $value) {

                $write_arr = [
                    'issue_question_id' => $value['id'],
                    'issue_question_type' => $value['type'],
                    'userAnswer' => $value['userAnswer'],
                    'issue_question_answer_remark' => $value['userRea'],
                    'question_info_id' => $question_info_id,
                    'questionnaire_id' => $data['info']['questionnaire_id']
                ];
                QuestionWrite::create($write_arr);
            }
        }
        return $this->response();

    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/9
     * @Time: 15:24
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 导入
     */
    public function importQuestion()
    {
        $id = $this->request->param('id', 3);
        $q = Questionnaire::find($id);
        $res = IssueQuestion::field('id,issue_question_title,issue_question_type,questionnaire_id')->with(['questionWrite.questionInfo'])->where(['questionnaire_id' => $id])->select()->toArray();
        $save_path = app()->getRootPath() . 'public/storage/' . 'import_question/';
        $headArr = [];
        $spreadsheet = new Spreadsheet();
        $objPHPExcel = $spreadsheet->getActiveSheet();
        $objPHPExcel->setTitle($q->title);  //设置当前sheet的标题
//        $headArr[] = '姓名';
//        if (intval($id) === 1) {
//            $headArr[] = '市县区';
//            $headArr[] = '年龄';
//            $headArr[] = '行业';
//        } else if (intval($id) === 2) {
//            $headArr[] = '市县区';
//            $headArr[] = '岗位';
//            $headArr[] = '网点名称';
//        } else {
//            $headArr[] = '市县区';
//            $headArr[] = '性别';
//            $headArr[] = '电话';
//        }
        $excel_data = [];
        foreach ($res as $key1 => $v) {

            $headArr[] = $v['issue_question_title'];
            $i = 0;
            foreach ($v['questionWrite'] as $key2 => $v1) {

                if (!empty($v1['issue_question_answer_remark'])) {
                    $beizhu = "[自定义:" . $v1['issue_question_answer_remark'] . "]"; //自定义的选择
                } else {
                    $beizhu = "";
                }
                $userAnswer_arr = explode(',', rtrim($v1['userAnswer'], ','));
                $ac = "";

                foreach ($userAnswer_arr as $k => $item) {
                    if (intval($v1['issue_question_type']) == 3){
                        $ac = $v1['userAnswer'];
                    }else{
                        $result = IssueQuestionAnswer::whereFindInSet('id',$item)->find();
                        if (is_null($result)) {
                            $ac = $v1['userAnswer'] . $beizhu;
                        } else {
                            $ac .= $result->issue_answer_title . ',' . $beizhu;
                        }

                    }

                }
//                $result = IssueQuestionAnswer::find($v1['userAnswer']);
//                if (is_null($result)) {
//                    $excel_data[$key2][] = $v1['userAnswer'] . $beizhu;
//                } else {
//                    $excel_data[$key2][] = $result->issue_answer_title . $beizhu;
//                }
                $excel_data[$key2][] = rtrim($ac, ',');
                $i++;
            }
        }
        $key = ord('A'); //65
        $key2 = ord("@"); //64
        foreach ($headArr as $v) {
            if ($key > ord("Z")) {
                $key2 += 1;
                $key = ord("A");
                $colum = chr($key2) . chr($key);//超过26个字母时才会启用  dingling 20150626
            } else {
                if ($key2 >= ord("A")) {
                    $colum = chr($key2) . chr($key);
                } else {
                    $colum = chr($key);
                }
            }
            $objPHPExcel->setCellValue($colum . '1', $v);
            $key += 1;
        }
        $column = 2;
        foreach ($excel_data as $key => $rows) { //行写入
            $span = ord("A");
            $span2 = ord("@");
            foreach ($rows as $k => $v) {
                if ($span > ord("Z")) {
                    $span2 += 1;
                    $span = ord("A");
                    $j = chr($span2) . chr($span);
                } else {
                    if ($span2 >= ord("A")) {
                        $j = chr($span2) . chr($span);
                    } else {
                        $j = chr($span);
                    }
                }
                //$j = chr($span);
                $objPHPExcel->setCellValue($j . $column, $v);
                $span++;
            }
            $column++;
        }
        $format = 'Xlsx';
        $filename = $q->title . '-' . time();
        header("Content-Disposition: attachment;filename=" . $filename . date('Y-m-d') . '.' . strtolower($format));
        header('Cache-Control: max-age=0');
        $objWriter = IOFactory::createWriter($spreadsheet, $format);
        $objWriter->save('php://output');
        //删除清空：
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }


    /**
     * @param $id
     * @User: 刘海龙
     * @Date: 2021/9/9
     * @Time: 15:36
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException\
     * 获取题目
     */
    public function getQuestionTopicList($id){

        $answer = IssueQuestionAnswer::find($id);
        if (is_null($answer)){
            return $this->response(403,'暂未找到题目');
        }
        $question = IssueQuestion::where(['questionnaire_id'=>$answer['questionnaire_id']])->select();
        return $this->response($question);
    }

    /**
     * @User: 刘海龙
     * @Date: 2021/9/9
     * @Time: 15:41
     * @return \think\response\Json
     * 保存跳题
     */
    public function saveJumpTopic()
    {
        $data = $this->request->param();
        $data['issue_answer_type'] = IssueQuestionAnswer::ISSUE_ANSWER_TYPE_THREE;

        IssueQuestionAnswer::update($data);
        return $this->response();
    }


    public function getQuestionInfo(){
        $data = $this->request->param();
        $create_id = $data['create_id'];

        $res = Questionnaire::with(['questionInfo'=>function($query) use($create_id){
            $query->where(['create_id'=>$create_id]);
            return $query;
        }])->select();

        return $this->response($res);
    }
}
